package com.example.ws.controller;

import com.example.ws.service.IMessageRankService;
import com.example.ws.service.IOnlineUserService;
import com.example.ws.service.RedisMessagePublisher;
import com.example.ws.vo.RestResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@Api(tags = "Redis测试接口")
public class TextController {
    @Autowired
    private IOnlineUserService onlineUserService;
    @Autowired
    private IMessageRankService IMessageRankService;
    @Autowired
    private RedisMessagePublisher redisMessagePublisher;

    @PostMapping("/GetUserOnline")
    @ApiOperation("获取在线用户列表")
    public RestResultVo<Set<String>> getOnlineUsers(
            @RequestParam(required = false) List<String> users // 支持批量添加用户
    ) {
        if (users != null) {
            users.forEach(onlineUserService::userLogin); // 批量添加在线用户
        }

        Set<String> onlineUsers = onlineUserService.getOnlineUsers();
        return RestResultVo.ok(onlineUsers);
    }

    @PostMapping("/GetPHB")
    @ApiOperation("获取消息排行榜")
    public RestResultVo<Set<ZSetOperations.TypedTuple<String>>> getMessageRanking(
            @RequestParam(required = false) List<String> users // 支持批量添加用户
    ) {
        if (users != null) {
            users.forEach(IMessageRankService::incrementMessageCount); // 批量增加消息计数
        }
        Set<ZSetOperations.TypedTuple<String>> topUsers = IMessageRankService.getTopUsers();
        return RestResultVo.ok(topUsers);
    }
    /**
     * 测试Redis消息发布
     * @param message 要发布的消息内容
     * @return 操作结果
     */
    @PostMapping("/publish")
    @ApiOperation("测试Redis消息发布")
    public String testPublish(@RequestParam String message) {
        try {
            redisMessagePublisher.publishMessage(message);
            return "消息发布成功: " + message;
        } catch (Exception e) {
            return "消息发布失败: " + e.getMessage();
        }
    }
}